import React, { useContext, useEffect, useMemo, useState } from 'react';
import { Button, Card, Empty, Form, Input, Space, message } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { UpdateRightContastsTop } from './UpdateRightContastsTop';
import { ISupplierActionEnum, SupplierLocaldataContext } from '../common';
import { PlusOutlined, EditOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { UpdateRightContactBody } from './UpdateRightContactBody';
import { ContactsUpdateModal } from './ContactsUpdateModal';
import { onMouseOutBtn } from '@/utils';
import { contactsDataGridServices } from '../services';

export const UpdateViewRight: React.FC = () => {
  /** 获取上下文 */
  const { contactsSwitchList, contactsCurrent, supplierDispath, curRes, reloadDetailInfo, locationID } = useContext(SupplierLocaldataContext);

  /** 展示联系人弹框 */
  const [contactsTableModal, setContactsTableModal] = useState<Record<string, any>>({
    contactsModalBool: false,
    currentContactsInfo: {},
  });

  /**
   * 接口回调
   * @param res
   */
  const contactsDataCallback = (res: any) => {
    if (res && res?.msgFlag) {
      if (res?.rows?.length > 0) {
        supplierDispath({
          type: ISupplierActionEnum.CHECKLIST_CONTACTS,
          payload: res?.rows || [],
        });
      }
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取资质列表 */
  const { getContactsPaneDataGrid, refreshContactsPane, contactsPaneloading } = contactsDataGridServices(curRes, locationID, contactsDataCallback);

  /**初始化 */
  useEffect(() => {
    if (locationID) {
      getContactsPaneDataGrid({}); //模拟数据-王志龙
    }
  }, [locationID]);

  /** 切换当前展示联系人 */
  const contactsSwitch = (switchType: string) => {
    let contacIndex: number = contactsCurrent;
    const dataLength = contactsSwitchList?.length;
    if (contacIndex <= dataLength) {
      if (switchType == 'prev') {
        contacIndex = contacIndex - 1;
      }
      if (switchType == 'next') {
        contacIndex = contacIndex + 1;
      }
      supplierDispath({
        type: ISupplierActionEnum.CONTACTS_CURRENT,
        payload: contacIndex,
      });
    }
  };

  /**
   * 删除联系人接口回调
   * @param res 接口返回数据
   */
  // const deleteContactsCallback = (res: any) => {
  //   if (res && res?.msgFlag) {
  //     message.success(res?.msg);
  //     reloadDetailInfo();
  //   } else {
  //     message.error(res?.msg);
  //   }
  // };

  /** 引入删除联系人接口 */
  // const { deleteContactsRun } = deleteContactsService(deleteContactsCallback);

  /** 卡片右侧操作按钮 */
  const contactsCardExtra = useMemo(() => {
    return (
      <>
        {contactsSwitchList?.length > 0 && (
          <Space>
            {/* {curRes?.['/supplierContacterController/delete'] && (
              <Popconfirm
                title={'确认要删除吗？删除后无法恢复！'}
                okText={'确认'}
                cancelText={'取消'}
                placement="bottom"
                arrowPointAtCenter={true}
                onConfirm={() => {
                  if (locationID) {
                    const delParams: Record<string, any> = {
                      id: contactsSwitchList?.[contactsCurrent]?.id,
                      supplierID: locationID,
                      versionNum: contactsSwitchList?.[contactsCurrent]?.versionNum,
                    };
                    deleteContactsRun(delParams);
                  } else {
                    const delNewContacts: Record<string, any>[] = contactsSwitchList?.filter(
                      (item: any) => item?.key !== contactsSwitchList?.[contactsCurrent]?.key,
                    );
                    supplierDispath({
                      type: ISupplierActionEnum.CHECKLIST_CONTACTS,
                      payload: delNewContacts,
                    });
                  }
                }}
              >
                <Button size="small" onMouseUp={onMouseOutBtn} icon={<DeleteOutlined />} type={'link'} className='manageBtntTxtStyle'>
                  删除
                </Button>
              </Popconfirm>
            )} */}

            <Form.Item name="attachContent" style={{ marginBottom: 0 }}>
              <Input
                placeholder="按姓名搜索"
                style={{ borderRadius: 50, width: 180 }}
                suffix={
                  <Space>
                    <a onClick={() => {}}>
                      <SearchOutlined />
                    </a>
                    <a onClick={() => {}}>
                      <ReloadOutlined />
                    </a>
                  </Space>
                }
              />
            </Form.Item>
            {curRes?.['/supplierContacterController/edit'] && (
              <Button
                size="small"
                onMouseUp={onMouseOutBtn}
                // icon={<EditOutlined />}
                type={'link'}
                className="manageBtntTxtStyle"
                onClick={() => {
                  setContactsTableModal({
                    contactsModalBool: true,
                    currentContactsInfo: contactsSwitchList?.[contactsCurrent],
                  });
                }}
              >
                编辑
              </Button>
            )}
          </Space>
        )}
        {curRes?.['/supplierContacterController/add'] && (
          <Button
            size="small"
            onMouseUp={onMouseOutBtn}
            // icon={<PlusOutlined />}
            type={'link'}
            className="manageBtntTxtStyle"
            onClick={() => {
              setContactsTableModal({
                contactsModalBool: true,
                currentContactsInfo: {},
              });
            }}
          >
            添加
          </Button>
        )}
      </>
    );
  }, [contactsCurrent, contactsSwitchList, curRes, locationID]);

  return (
    <>
      <Card title={'相关联系人'} className={pageStyles['page-view-cardView']} bodyStyle={{ padding: 0 }} extra={<Form>{contactsCardExtra}</Form>}>
        {contactsSwitchList?.length > 0 ? (
          <div className={'CardBodyScrollBarLayout'}>
            <UpdateRightContastsTop contactsCurrentIndex={contactsCurrent} contactsCurrentChange={contactsSwitch} />
            <UpdateRightContactBody contactsCurrentIndex={contactsCurrent} />
          </div>
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
        )}
      </Card>

      {/* 联系人弹框 */}
      {contactsTableModal?.contactsModalBool && (
        <ContactsUpdateModal
          onClose={() => {
            setContactsTableModal({
              contactsModalBool: false,
              currentContactsInfo: {},
            });
          }}
          currentContactsInfo={contactsTableModal?.currentContactsInfo}
        />
      )}
    </>
  );
};
